import json
import logging
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.hunyuan.v20230901 import hunyuan_client, models
from typing import Any, Optional, Union, Generator, TYPE_CHECKING

if TYPE_CHECKING:
    from tencentcloud.hunyuan.v20230901.models import ChatCompletionsResponse

logger = logging.getLogger("DailyInspection")

class LongCatAnalyzer:
    def __init__(self, secret_id, secret_key, region="ap-beijing"):
        # 腾讯云认证
        self.cred = credential.Credential(secret_id, secret_key)
        
        # 客户端配置
        http_profile = HttpProfile()
        http_profile.endpoint = "hunyuan.tencentcloudapi.com"
        
        client_profile = ClientProfile()
        client_profile.httpProfile = http_profile
        
        # 创建客户端
        self.client = hunyuan_client.HunyuanClient(self.cred, region, client_profile)
        
    def analyze_metrics(self, metrics_data) -> Optional[str]:
        """使用腾讯云Hunyuan进行指标分析"""
        prompt = self._build_prompt(metrics_data)
        
        try:
            # 构建请求参数
            req = models.ChatCompletionsRequest()
            req.Model = "hunyuan-turbo"
            req.Messages = [
                {
                    "Role": "system",
                    "Content": (
                        "你是一个专业的SRE工程师，需要根据Prometheus指标数据：\n"
                        "1. 分析当前系统健康状况\n"
                        "2. 识别潜在异常指标\n"
                        "3. 给出具体的解决建议\n"
                        "4. 用技术报告格式输出结果\n"
                        "5. 如果无异常则输出'[正常]'开头"
                    )
                },
                {
                    "Role": "user",
                    "Content": prompt
                }
            ]
            req.Temperature = 0.3
            req.TopP = 0.8
            # 注释掉不存在的 MaxTokens 属性
            # req.MaxTokens = 2048
            
            # 调用API
            response = self.client.ChatCompletions(req)
            
            # 使用类型转换来避免类型检查错误
            resp: "ChatCompletionsResponse" = response  # type: ignore
            
            # 提取回复内容
            if resp and hasattr(resp, 'Choices') and resp.Choices:
                choice = resp.Choices[0]
                if hasattr(choice, 'Message') and choice.Message:
                    message = choice.Message
                    if hasattr(message, 'Content') and message.Content:
                        return message.Content
            
            logger.error("Hunyuan API返回空响应或响应格式不正确")
            return None
                
        except Exception as e:
            logger.error(f"Hunyuan分析失败: {e}")
            return None
            
    def _build_prompt(self, data):
        """构建分析提示（与原来相同）"""
        from datetime import datetime
        
        prompt = f"以下是过去24小时的Prometheus监控数据({datetime.now().strftime('%Y-%m-%d')}):\n\n"
        
        for metric_type, info in data.items():
            prompt += f"【{metric_type.upper()}】\n"
            if "data" in info and "data" in info["data"] and "result" in info["data"]["data"]:
                series = info["data"]["data"]["result"]
                for s in series[:3]:  # 取前3个监控序列
                    metric_name = s["metric"].get("__name__", list(s["metric"].values())[0])
                    latest_val = s["values"][-1][1] if s["values"] else "无数据"
                    prompt += f"- {metric_name}: 最新值={latest_val}\n"
                    
                if len(series) > 3:
                    prompt += f"- ...还有{len(series)-3}个监控序列\n"
            else:
                prompt += "- 数据获取异常\n"
            prompt += "\n"
            
        prompt += (
            "请分析：\n"
            "1. 哪些指标超出正常范围？\n"
            "2. 哪些趋势可能产生问题？\n"
            "3. 建议的紧急程度和应对措施？\n"
        )
        return prompt